//
//  WCBAddressListTableViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBAddressListTableViewController.h"
#import "UIColor+Extend.h"
#import "WCASessionManager.h"
#import "WCBAdressModel.h"
#import "WCBAdressListTableViewCell.h"
#import "WCBAdressViewModel.h"
#import "WCBAddAdressTableViewController.h"
#import "UIScreen+Extend.h"
#import "WCBPayViewController.h"
#import "WCBPayViewController.h"
#import "TFToast.h"
#import "WCBDataHelper.h"
#import "UIImage+Ex.h"

static NSString *const wcbAdressTbaleViewCellId = @"WCBAdressListTableViewCell";

@interface WCBAddressListTableViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)WCBAdressModel *seleectAdressModel;
/**
 收货地址的数组
 */
@property(nonatomic,strong)NSMutableArray *addressModelArray;

@property(nonatomic,strong) UITableView *tableView;

/**
 去支付按钮
 */
@property(nonatomic,strong) UIButton *toPay;

@property (strong, nonatomic) UIActivityIndicatorView *activityIndicatorView;

@end

@implementation WCBAddressListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // TODO: 测试，需要删除
    [[WCASessionManager manager].requestHeaderFieldValueDictionary setObject:@"778831979676" forKey:@"USERID"];
    
    self.view.backgroundColor = [UIColor r:239 g:239 b:239];
    
    [self p_setUpNav];
    
    // 设置导航条相关的
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.toPay];
    
    CGRect frame = self.tableView.frame;
    frame.size.height -= 100;
    self.tableView.frame = frame;
    
    [self p_requestAddressData];
    
    [self.tableView registerClass:[WCBAdressListTableViewCell class] forCellReuseIdentifier:wcbAdressTbaleViewCellId];
    self.tableView.tableFooterView = [[UIView alloc] init];
}

- (UIActivityIndicatorView *)activityIndicatorView
{
    if (!_activityIndicatorView) {
        _activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0,0,100,100)];
        _activityIndicatorView.center = self.view.center;
        [_activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [_activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_activityIndicatorView setBackgroundColor:[UIColor lightGrayColor]];
        [self.view addSubview:_activityIndicatorView];
    }
    return _activityIndicatorView;
}

#pragma mark - parvate
-(void)p_setUpNav{
    self.title = @"选择收货地址";
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 140, 40);
    [button setTitle:@"新增收货地址" forState: UIControlStateNormal];
    [button setTitleColor:[UIColor r:12 g:95 b:245] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onRightNavClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

-(void)p_showAlertWithString:(NSString *)string{
    UIAlertController *alert  = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
#pragma mark - action

/**
 点击的新增收货地址
 */
- (void)onRightNavClick:(UIBarButtonItem *)button{
    WCBAddAdressTableViewController *addAdressVC = [[WCBAddAdressTableViewController alloc]init];
    __weak WCBAddressListTableViewController * weak_self = self;
    addAdressVC.saveCompleteBlock = ^(BOOL success) {
        [weak_self p_requestAddressData];
    };
    [self.navigationController pushViewController:addAdressVC animated:YES];
}

- (void)toPayClick:(UIButton *)button
{
    if (self.seleectAdressModel) {
        [self loadService];
    }
    else {
        [TFToast toast:@"请选择收货地址"];
    }
}

- (void)loadService
{
    NSDictionary *param = @{ @"addressId" : self.seleectAdressModel.id,
                             @"bookId"    : self.bookModel.bookId,
                             @"dealerCode": WCBDataHelper.sharedHelper.buniessCode,
                             @"userId"    : [WCBDataHelper.sharedHelper getCurrentUserModel].userId
                             };
    
    [self.activityIndicatorView startAnimating];
    __weak WCBAddressListTableViewController *_self = self;
    [WCASessionManager POST:@"weimport/mtime/getPayQRCode" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"getPayQRCode :%@", responseObject);
        
        NSString *code = [responseObject objectForKey:@"code"];
        BOOL success = [code isEqualToString:@"000"];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_self.activityIndicatorView stopAnimating];
                
                WCBPayViewController *vc = [[WCBPayViewController alloc] init];
                vc.bookModel = _self.bookModel;
                vc.addressModel = _self.seleectAdressModel;
                vc.payModel = [WCBPayModel modelWithDict:responseObject[@"data"]];
                [_self.navigationController pushViewController:vc animated:YES];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_self.activityIndicatorView stopAnimating];
                [TFToast toast:@"获取数据失败，请稍候重试"];
            });
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [_self.activityIndicatorView stopAnimating];
            [TFToast toast:@"您的网络不给力，请检查网络后重试!"];
        });
    }];
}

#pragma mark - network

/**
 请求收货地址信息
 */
-(void)p_requestAddressData{
    
    [self.addressModelArray removeAllObjects];
    [WCASessionManager POST:@"tfmobile/cartM/addressList"
                 parameters:@{@"isGzip" : @"0"}
                    success:^(NSURLSessionDataTask *task, id responseObject) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([[responseObject objectForKey:@"status"] boolValue])
                            {
                                NSArray *adressDicArray = [responseObject objectForKey:@"dataList"];
                                
                                for (NSDictionary * dic in adressDicArray)
                                {
                                    WCBAdressModel *adressModel = [WCBAdressModel modelWithDict:dic];
                                    WCBAdressViewModel *viewModel = [[WCBAdressViewModel alloc]init];
                                    if (!self.seleectAdressModel)
                                    {// 如果界面上没有选中的，则默认选中 默认地址
                                        if ([adressModel.isdefault isEqualToString:@"1"]) {
                                            viewModel.isSelect = YES;
                                            self.seleectAdressModel = adressModel;
                                        }
                                    }
                                    else
                                    {
                                        if ([adressModel.id isEqualToString:self.seleectAdressModel.id]) {
                                            viewModel.isSelect = YES;
                                        }
                                    }
                                    
                                    viewModel.model = adressModel;
                                    
                                    [self.addressModelArray addObject:viewModel];
                                }
                                if (self.addressModelArray.count == 0) {
                                    [self onRightNavClick:nil];
                                    return ;
                                }
                                [self.tableView reloadData];
                                
                                
                            }
                            else{
                                [self p_showAlertWithString:[responseObject objectForKey:@"info" ]];
                            }
                        });
                    }
                    failure:^(NSURLSessionDataTask *task, NSError *error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self p_showAlertWithString:@"收货地址列表请求失败"];
                        });
                    }];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.addressModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WCBAdressListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:wcbAdressTbaleViewCellId forIndexPath:indexPath];
    WCBAdressViewModel *viewModel =self.addressModelArray[indexPath.row];
    cell.viewModel = viewModel;
    __weak WCBAddressListTableViewController * weak_self = self;
    cell.selectBlock = ^(WCBAdressViewModel *viewModel) {
        for (WCBAdressViewModel *tempViewModel in weak_self.addressModelArray) {
            if (tempViewModel.model.id == viewModel.model.id) {
                tempViewModel.isSelect = YES;
                weak_self.seleectAdressModel = tempViewModel.model;
            }
            else{
                tempViewModel.isSelect = NO;
            }
        }
        [weak_self.tableView reloadData];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WCBAdressViewModel *viewModel = self.addressModelArray[indexPath.row];
    return 70 + viewModel.adressHeight ;
}


//执行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    WCBAdressViewModel *viewModel = self.addressModelArray[indexPath.row];
    
    __weak WCBAddressListTableViewController *_self = self;
    [WCASessionManager POST:@"tfmobile/cartM/delAddress"
                 parameters:@{@"id":viewModel.model.id}
                    success:^(NSURLSessionDataTask *task, id responseObject) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                        
                            [_self.addressModelArray removeObjectAtIndex:indexPath.row];
                            [_self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            
                            if ([_self.seleectAdressModel.id isEqualToString:viewModel.model.id]) {
                                _self.seleectAdressModel = nil;
                            }
                        });
                    }
                    failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [_self p_showAlertWithString:@"删除失败"];
                    }];
    
    
}
//侧滑出现的文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return @"删除";
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    WCBAdressViewModel *viewModel = self.addressModelArray[indexPath.row];
    WCBAddAdressTableViewController *addAdressVC = [[WCBAddAdressTableViewController alloc]init];
    addAdressVC.edit = YES;
    addAdressVC.adressViewModel = viewModel;
    __weak WCBAddressListTableViewController * weak_self = self;
    addAdressVC.saveCompleteBlock = ^(BOOL success) {
        [weak_self p_requestAddressData];
    };
    [self.navigationController pushViewController:addAdressVC animated:YES];
}

#pragma mark - lazy -load
-(NSMutableArray *)addressModelArray{
    if (_addressModelArray == nil) {
        _addressModelArray = [NSMutableArray array];
    }
    return _addressModelArray;
}

-(UITableView *)tableView{
    if (!_tableView ) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
    
    }
    return _tableView;
}

-(UIButton *)toPay{
    if (!_toPay) {
        _toPay = [UIButton buttonWithType:UIButtonTypeCustom];
        
        CGFloat x, y, w, h;
        x = 50.f;
        y = [UIScreen height] - 80;
        w = [UIScreen width] - 2 * x;
        h = 60;
        _toPay.frame = CGRectMake(x, y, w, h);
        _toPay.backgroundColor = [UIColor r:31 g:156 b:239];
        
        [_toPay setBackgroundImage:[UIImage tf_imageWithColor:[UIColor colorWithRed:0.11 green:0.62 blue:0.94 alpha:1.00]] forState:UIControlStateNormal];
        [_toPay setBackgroundImage:[UIImage tf_imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
        
        [_toPay setTitle:@"去支付" forState:UIControlStateNormal];
        _toPay.titleLabel.font = [UIFont systemFontOfSize:23];
        [_toPay setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _toPay.layer.cornerRadius = 5;
        _toPay.clipsToBounds = YES;
        [_toPay addTarget:self action:@selector(toPayClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toPay;
}


- (void)dealloc {
    NSLog(@"\n**************\n%@\n*************\n",NSStringFromClass(self.class));
   
}
@end
